# 创建新的图片采集页面
<template>
  <div class="crawler-container">
    <a-card :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-area">
        <a-space>
          <!-- 自定义搜索框 -->
          <div class="custom-search-box">
            <div class="search-input-wrapper">
              <input
                v-model="searchText"
                type="text"
                placeholder="输入搜索关键词"
                class="search-input"
                @keyup.enter="fetchImages"
              />
              <div v-if="searchText" class="clear-icon" @click="clearSearch">
                <CloseOutlined />
              </div>
            </div>
          </div>
          <a-input-number
            v-model:value="count"
            :min="1"
            :max="50"
            style="width: 120px"
            size="large"
            placeholder="图片数量"
          />
          <a-button type="primary" size="large" @click="fetchImages" :loading="loading">
            <template #icon><SearchOutlined /></template>
            获取图片
          </a-button>
          <a-button :type="isAllSelected ? 'primary' : 'default'" size="large" @click="selectAll">
            <template #icon><SelectOutlined /></template>
            {{ isAllSelected ? '取消全选' : '全选本页' }}
          </a-button>
          <a-button
            type="primary"
            size="large"
            :disabled="selectedImages.length === 0"
            @click="handleDownloadAndUpload"
          >
            <template #icon><UploadOutlined /></template>
            下载并上传 ({{ selectedImages.length }})
          </a-button>
        </a-space>
      </div>

      <!-- 图片展示区域 -->
      <a-spin :spinning="loading" tip="加载中..." size="large">
        <div class="image-grid">
          <div v-for="image in images" :key="image.id" class="image-item">
            <div class="image-card">
              <div class="select-overlay" @click.stop="toggleSelect(image)">
                <a-checkbox :checked="isSelected(image)" />
              </div>
              <div class="image-wrapper">
                <img
                  :src="image.url"
                  :alt="image.description || '暂无描述'"
                  class="image"
                  @error="handleImageError"
                />
              </div>
            </div>
          </div>
        </div>
      </a-spin>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed } from 'vue'
  import { message } from 'ant-design-vue'
  import { SearchOutlined, SelectOutlined, UploadOutlined, CloseOutlined } from '@ant-design/icons-vue'
  import { useRouter } from 'vue-router'
  import { crawlerPicturesUsingGet } from '@/api/tupianguanlijiekou'

  // 类型定义
  interface CrawlerImage {
    id: string
    url: string
    description: string
  }

  // 状态定义
  const loading = ref(false)
  const searchText = ref('')
  const count = ref(20)
  const images = ref<CrawlerImage[]>([])
  const selectedImages = ref<CrawlerImage[]>([])
  const router = useRouter()

  // 图片错误处理
  const handleImageError = (e: Event) => {
    const img = e.target as HTMLImageElement
    img.src = '/src/assets/default_image.png'
  }

  // 清除搜索框内容
  const clearSearch = () => {
    searchText.value = ''
  }

  // 获取图片列表
  const fetchImages = async () => {
    if (!searchText.value) {
      message.warning('请输入搜索关键词')
      return
    }

    if (count.value > 50) {
      message.warning('最多获取50张图片')
      count.value = 50
      return
    }

    loading.value = true
    try {
      // 调用后端API
      const response = await crawlerPicturesUsingGet({
        searchText: searchText.value,
        count: Number(count.value),
      })

      const { code, data } = response.data
      if (code !== 200 || !data) {
        throw new Error('获取图片失败')
      }

      const imageList = data.list || []
      const newImages = imageList.map((item: { url: string; title: string }, index: number) => ({
        id: `crawler-${index}-${Date.now()}`,
        url: item.url,
        description: item.title,
      }))

      images.value = newImages
      message.success(`成功获取 ${newImages.length} 张图片`)
    } catch (error: unknown) {
      console.error('获取图片失败：', error)
      const errorMessage = error instanceof Error ? error.message : '未知错误'
      message.error('获取图片失败：' + errorMessage)
    } finally {
      loading.value = false
    }
  }

  // 切换选择状态
  const toggleSelect = (image: CrawlerImage) => {
    const index = selectedImages.value.findIndex(img => img.id === image.id)
    if (index === -1) {
      selectedImages.value.push(image)
    } else {
      selectedImages.value.splice(index, 1)
    }
  }

  // 检查是否被选中
  const isSelected = (image: CrawlerImage) => {
    return selectedImages.value.some(img => img.id === image.id)
  }

  // 全选功能
  const selectAll = () => {
    if (images.value.every(img => isSelected(img))) {
      selectedImages.value = []
    } else {
      selectedImages.value = [...images.value]
    }
  }

  // 检查是否全选
  const isAllSelected = computed(() => {
    return images.value.length > 0 && images.value.every(img => isSelected(img))
  })

  // 下载并上传处理
  const handleDownloadAndUpload = async () => {
    if (selectedImages.value.length === 0) {
      message.warning('请先选择图片')
      return
    }

    try {
      // 完全匹配 UnsplashPic.vue 的数据结构
      const imageInfos = selectedImages.value.map(image => ({
        id: image.id,
        url: image.url,
        description: image.description || '',
        alt_description: image.description || '',
        user: {
          name: '',
        },
        urls: {
          regular: image.url,
        },
      }))

      // 使用与 UnsplashPic.vue 相同的 sessionStorage key
      sessionStorage.setItem('unsplashPendingImages', JSON.stringify(imageInfos))

      message.success(`已选择 ${selectedImages.value.length} 张图片`)
      router.push('/user/createPicture?from=unsplash&total=' + selectedImages.value.length)
    } catch (error) {
      message.error('处理图片失败，请重试')
      console.error('处理图片失败:', error)
    }
  }
</script>

<style scoped>
  .crawler-container {
    padding: 24px;
    background: var(--theme-background);
    min-height: 100vh;
    transition: all 0.3s ease;
  }

  /* 自定义搜索框样式 */
  .custom-search-box {
    width: 200px;
  }

  .search-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background: var(--theme-surface);
    border: 1px solid var(--theme-border);
    border-radius: 6px;
    transition: all 0.3s ease;
    overflow: hidden;
  }

  .search-input-wrapper:hover {
    border-color: var(--theme-primary);
  }

  .search-input-wrapper:focus-within {
    border-color: var(--theme-primary);
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  .search-input {
    flex: 1;
    height: 40px;
    padding: 8px 40px 8px 12px;
    background: transparent;
    border: none;
    outline: none;
    font-size: 14px;
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  .search-input::placeholder {
    color: var(--theme-textSecondary);
  }

  .clear-icon {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--theme-textSecondary);
    cursor: pointer;
    transition: all 0.3s ease;
    border-radius: 50%;
  }

  .clear-icon:hover {
    color: var(--theme-error);
    background: var(--theme-background);
  }

  .search-area {
    margin-bottom: 24px;
  }

  .image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
    padding: 16px 0;
  }

  .image-item {
    position: relative;
    aspect-ratio: 1;
  }

  .image-card {
    position: relative;
    cursor: pointer;
    border-radius: 8px;
    overflow: hidden;
    background: var(--theme-surface);
    box-shadow: 0 2px 8px var(--theme-shadow);
    border: 1px solid var(--theme-border);
    transition: all 0.3s ease;
  }

  .image-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px var(--theme-shadow);
    border-color: var(--theme-primary);
  }

  .image-wrapper {
    position: relative;
    width: 100%;
    height: 200px;
    background: var(--theme-background);
    overflow: hidden;
    transition: all 0.3s ease;
  }

  .image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
  }

  .select-overlay {
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 2;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
    padding: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 1px solid var(--theme-border);
  }

  /* 深色主题下的选择覆盖层 */
  [data-theme="dark"] .select-overlay {
    background: rgba(0, 0, 0, 0.8);
    border-color: var(--theme-border);
  }

  /* 深色主题下的选择覆盖层 */
  [data-theme="dark"] .select-overlay:hover {
    background: rgba(0, 0, 0, 0.9);
    border-color: var(--theme-primary);
  }

  /* 浅色主题下的选择覆盖层 */
  [data-theme="light"] .select-overlay:hover {
    background: rgba(255, 255, 255, 1);
    border-color: var(--theme-primary);
    box-shadow: 0 2px 8px var(--theme-shadow);
  }

  /* 卡片主题适配 */
  :deep(.ant-card) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    box-shadow: 0 2px 8px var(--theme-shadow);
    transition: all 0.3s ease;
  }

  :deep(.ant-card-body) {
    background: var(--theme-surface);
    transition: all 0.3s ease;
  }

  /* 输入框主题适配 */
  :deep(.ant-input) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  :deep(.ant-input:hover) {
    border-color: var(--theme-primary);
  }

  :deep(.ant-input:focus) {
    border-color: var(--theme-primary);
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  :deep(.ant-input::placeholder) {
    color: var(--theme-textSecondary);
  }

  /* 数字输入框主题适配 */
  :deep(.ant-input-number) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  :deep(.ant-input-number:hover) {
    border-color: var(--theme-primary);
  }

  :deep(.ant-input-number:focus),
  :deep(.ant-input-number-focused) {
    border-color: var(--theme-primary);
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  :deep(.ant-input-number-input) {
    background: transparent;
    color: var(--theme-text);
    font-size: 14px;
  }

  :deep(.ant-input-number-input::placeholder) {
    color: var(--theme-textSecondary);
  }

  :deep(.ant-input-number-handler-wrap) {
    background: var(--theme-surface);
    border-left: 1px solid var(--theme-border);
  }

  :deep(.ant-input-number-handler) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-textSecondary);
    transition: all 0.3s ease;
  }

  :deep(.ant-input-number-handler:hover) {
    background: var(--theme-background);
    color: var(--theme-primary);
  }

  :deep(.ant-input-number-handler-down) {
    border-top: 1px solid var(--theme-border);
  }

  /* 按钮主题适配 */
  :deep(.ant-btn) {
    transition: all 0.3s ease;
  }

  :deep(.ant-btn-default) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
  }

  :deep(.ant-btn-default:hover) {
    border-color: var(--theme-primary);
    color: var(--theme-primary);
  }

  :deep(.ant-btn-primary) {
    background: var(--theme-primary);
    border-color: var(--theme-primary);
    color: var(--theme-surface);
  }

  :deep(.ant-btn-primary:hover) {
    background: var(--theme-secondary);
    border-color: var(--theme-secondary);
    color: var(--theme-surface);
  }

  /* 复选框主题适配 */
  :deep(.ant-checkbox) {
    transition: all 0.3s ease;
  }

  :deep(.ant-checkbox .ant-checkbox-inner) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    transition: all 0.3s ease;
  }

  :deep(.ant-checkbox:hover .ant-checkbox-inner) {
    border-color: var(--theme-primary);
  }

  :deep(.ant-checkbox-checked .ant-checkbox-inner) {
    background: var(--theme-primary);
    border-color: var(--theme-primary);
  }

  /* 加载状态主题适配 */
  :deep(.ant-spin) {
    color: var(--theme-primary);
  }

  :deep(.ant-spin-dot-item) {
    background-color: var(--theme-primary);
  }

  /* 响应式设计 */
  @media (max-width: 1200px) {
    .image-grid {
      grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    }
  }

  @media (max-width: 992px) {
    .image-grid {
      grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    }
  }

  @media (max-width: 768px) {
    .image-grid {
      grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
      gap: 12px;
    }
    
    .crawler-container {
      padding: 16px;
    }
  }

  @media (max-width: 576px) {
    .image-grid {
      grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
      gap: 8px;
    }
    
    .image-wrapper {
      height: 150px;
    }
    
    .search-area {
      margin-bottom: 16px;
    }
  }
</style>
